package ofpof.service.mail;

import java.util.HashMap;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;

public class MessageCreator {

	private String fromEmail;
	private VelocityConfigurer velocityConfigurer;
	private HashMap<String, Object> attributesMap = new HashMap<String, Object>();
	
	public MessageCreator(VelocityConfigurer velocityConfigurer) {
		this.velocityConfigurer = velocityConfigurer;
	}

	public MimeMessagePreparator createMessage(final EmailCommand emailCommand) {
		final VelocityEngine velocityEngine = velocityConfigurer.getVelocityEngine();
		
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
				message.setTo(emailCommand.getTo());
				message.setFrom(fromEmail);
				emailCommand.getModel().putAll(attributesMap);
				String text = VelocityEngineUtils.mergeTemplateIntoString(
						velocityEngine, emailCommand.getTemplate(),
						emailCommand.getModel());
				message.setText(text, true);
			}
		};
		return preparator;
	}

	public void setFromEmail(String fromEmail) {
		this.fromEmail = fromEmail;
	}

	public void setAttributesMap(HashMap<String, Object> attributesMap) {
		this.attributesMap = attributesMap;
	}
}
